package com.easylinkin.linkappapi.security.config.admin;

import com.easylinkin.linkappapi.operatelog.entity.CommonOperateLog;
import com.easylinkin.linkappapi.operatelog.service.CommonOperateLogService;
import com.easylinkin.linkappapi.security.config.LoginCountCheck;
import com.easylinkin.sm.entity.User;
import com.easylinkin.sm.entity.UserLoginInfo;
import com.easylinkin.sm.service.LogService;
import com.easylinkin.sm.service.UserLoginInfoService;
import com.easylinkin.sm.service.UserService;
import java.util.Date;
import java.util.Objects;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.stereotype.Component;
import site.morn.boot.web.Responses;
import site.morn.rest.RestBuilders;
import site.morn.rest.RestMessage;

/**
 * 认证失败处理者
 *
 * @author timely-rain
 * @since 1.2.0, 2019/8/29
 */
@Component
public class RestAuthenticationFailureHandler implements AuthenticationFailureHandler {

  @Autowired
  private UserLoginInfoService userLoginInfoService;
  @Autowired
  private UserService userService;
  @Autowired
  private LogService logService;
  @Resource
  private LoginCountCheck loginCountCheck;  
  @Resource
  private CommonOperateLogService commonOperateLogService;


  @Override
  public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response,
      AuthenticationException exception) {

    String username = request.getParameter("username");
    User user = userService.findByUsername(username);

    RestMessage message = RestBuilders.failureBuilder().code("login.failure")
        .message(exception.getMessage()).build();

    if (Objects.nonNull(user)) {
//      saveLog(request, user, JsonUtils.toString(message));
      saveLoginInfo(user);
    }

    CommonOperateLog commonOperateLog = new CommonOperateLog();
    commonOperateLog.setTenantId("operation_management_user");
    commonOperateLog.setModuleName("登录");
    commonOperateLog.setContent("管理端登录失败");
    commonOperateLog.setUserAccount(username);
    commonOperateLog.setCreateTime(new Date()).setResult(false);
    commonOperateLogService.addLog(commonOperateLog);

    //    错误次数记录 达到规定次数 锁定规定时间
    if (user != null && user.getUsername() != null) {
      loginCountCheck.afterLoginHandler(false, user.getUsername());
    }
    Responses.standard(response).respond(message);
  }

  /**
   * 记录登录日志
   *
   * @param request 请求
   * @param user 用户
   * @param responseMessage 响应消息
   */
//  private void saveLog(HttpServletRequest request, User user, String responseMessage) {
//    //Department department = departmentService.get(user.getDepartmentId());
//    Log log = new Log();
//    log.setModuleId(Long.parseLong(Module.LOGIN));
//    log.setIp(request.getRemoteAddr());
//    log.setContent("用户登录");
//    log.setStatus(false);
//    log.setDisplay(true);
//    //log.setCustomerId(department.getCustomerId());
//    log.setResponseInformation(responseMessage);
//    logService.add(log);
//  }

  /**
   * 记录登录次数
   *
   * @param user 用户
   */
  private void saveLoginInfo(User user) {
    UserLoginInfo userLoginInfo = userLoginInfoService.get(user.getId());

    if (Objects.nonNull(userLoginInfo)) {
      userLoginInfoService.addErrorCount(user.getId());
    } else {
      //第一次登陆错误
      userLoginInfo = new UserLoginInfo();
      userLoginInfo.setUserId(user.getId());
      userLoginInfo.setErrorTime(new Date());
      userLoginInfo.setErrorCount(1);
      userLoginInfoService.add(userLoginInfo);
    }
  }
}
